﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using PlanningGIS.Oracle;
using PlanningGIS.Util;
using System.Collections;
using PlanningGIS.Win.Controls;
using ESRI.ArcGIS.Carto;
using PlanningGIS.Util.Log;

/// <summary>
///作用：栅格数据查询
///作者：盛琦
///编写日期：2013-09-24
/// </summary>
namespace PlanningGIS.Raster
{
    /// <summary>
    /// 
    /// </summary>
    public partial class FrmRasterQry :  Office2007Form
    {
        /// <summary>
        /// 
        /// </summary>
        private string m_tableName;
        /// <summary>
        /// 
        /// </summary>
        private string raster_type = "";
        /// <summary>
        /// 
        /// </summary>
        private IMap pMap;

        private string cur_col = "";

        #region 私有函数
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private List<ValueName> GetFieldLst(string tableName)
        {
            List<ValueName> filedNames = new List<ValueName>();
            string sql = "select * from " + tableName + " where 1=0"; //主要为了获取表结构与数据类型

            //Hashtable ht = oracleContet.GetColumnComments(tableName);

            DataTable dt = RasterHelper.DbConfig.Context.GetDataTable(sql);
            foreach (System.Data.DataColumn dc in dt.Columns)
            {
                if ("id".Equals(dc.ColumnName, StringComparison.CurrentCultureIgnoreCase))
                    continue;
                filedNames.Add(new ValueName()
                {
                    Value = dc.ColumnName,
                    Name =dc.ColumnName,// ht[dc.ColumnName].ToString(),
                    TagString = dc.DataType.ToString()
                });
            }

            return filedNames;
        }
        #endregion

        public IMap Map
        {
            set { pMap = value; }
        }

        public FrmRasterQry()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cboRasterType_SelectedIndexChanged(object sender, EventArgs e)
        {

            listFields.DataSource = null;
            listFields.Items.Clear();

            listValue.Items.Clear();

            txtSql.Text = "";

            try
            {

                if (cboRasterType.SelectedItem.ToString().ToUpper() == "DOM")
                {
                    m_tableName = "md_cq_dom";
                }
                else if (cboRasterType.SelectedItem.ToString().ToUpper() == "DEM")
                {
                    m_tableName = "md_cq_dem";
                }
                else
                {
                    return;
                }

                lblTabName.Text = m_tableName.ToUpper();

                List<ValueName> fields = GetFieldLst(m_tableName);

                listFields.ValueMember = "Value";
                listFields.DisplayMember = "Name";

                listFields.DataSource = fields;
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("读取栅格元数据表失败：" + ex.Message);
            }
        }

        private void cmdOperator_Click(object sender, EventArgs e)
        {
            ButtonX btn = sender as ButtonX;
            string op = " " + btn.Text.ToLower() + " ";

            int idx = txtSql.SelectionStart;
            string before = txtSql.Text.Substring(0, idx);
            string after = txtSql.Text.Substring(idx, txtSql.Text.Length - idx);

            txtSql.Text = before + op + after;

            txtSql.SelectionStart = before.Length + op.Length;
        }

        private void cmdGetUnique_Click(object sender, EventArgs e)
        {
            listValue.Items.Clear();

            try
            {
                string sql = "select distinct(" + listFields.Text + ") from " + m_tableName;
                DataTable dt = RasterHelper.DbConfig.Context.GetDataTable(sql);

                foreach (DataRow dr in dt.Rows)
                {
                    listValue.Items.Add(dr[0].ToString());
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("获取字段唯一值失败:" + ex.Message);
            }
        }

        private void FrmRasterQry_Load(object sender, EventArgs e)
        {
            foreach (Control ctl in gbOpreator.Controls)
            {
                if (ctl is ButtonX)
                {
                    (ctl as ButtonX).Click += cmdOperator_Click;
                }
            }

            try
            {
                if (!RasterHelper.DbConfig.Context.CanConncect())
                {
                    MsgHelper.ShowWarningMsgbox("记录栅格数据的元数据库连接失败，请核查！");
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                MsgHelper.ShowWarningMsgbox("记录栅格数据的元数据库连接失败，请核查！");
                this.Close();
            }

            cboRasterType.SelectedIndex = 0;
            cboMethod.SelectedIndex = 0;

        }

        private void listFields_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int idx = txtSql.SelectionStart;
            string before = txtSql.Text.Substring(0, idx );
            string after = txtSql.Text.Substring(idx, txtSql.Text.Length - idx);

            txtSql.Text = before + listFields.Text + after;

            txtSql.SelectionStart = before.Length + listFields.Text.Length;
        }

        private void listValue_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int idx = txtSql.SelectionStart;
            string before = txtSql.Text.Substring(0, idx );
            string after = txtSql.Text.Substring(idx, txtSql.Text.Length - idx);

            string value = "";

            string sql = "select data_type from user_tab_columns where table_name = '" + m_tableName.ToUpper() + "' and  column_name = '" + listFields.Text + "'";

            string dataType = RasterHelper.DbConfig.Context.GetScalar(sql).ToString().ToLower();

            switch (dataType)
            {
                case "number":
                    value = listValue.Text;
                    break;

                case "varchar2":
                case "nvarchar2":
                    value = "\'" + listValue.Text + "\'";
                    break;

                case "date":
                    value = " TO_DATE('" + listValue.Text + "','YYYY-MM-DD HH24:MI:SS')";
                    break;

                default :
                    return;
            }

            txtSql.Text = before + value + after;

            txtSql.SelectionStart = before.Length + value.Length;
        }

        private void listFields_MouseClick(object sender, MouseEventArgs e)
        {
            if (listFields.Text != cur_col) listValue.Items.Clear();

            cur_col = listFields.Text;
        }

        private void cmdClear_Click(object sender, EventArgs e)
        {
            txtSql.Text = "";
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                FrmShop frmShop = FrmShop.GetShopFrm();

                if (cboMethod.SelectedIndex != 0 &&( raster_type != m_tableName ||frmShop.HasClear))
                {
                    MsgHelper.ShowWarningMsgbox("对于不同类型的栅格数据，或者购物车被清空后不能进行结果的追加与合并！");
                    return;
                }

                string sql = "select * from " + m_tableName + ((txtSql.Text == "") ? "" : (" where " + txtSql.Text));
                DataTable dt = RasterHelper.DbConfig.Context.GetDataTable(sql);

                frmShop.Map = pMap;
                frmShop.Add2Shop(dt, cboMethod.SelectedIndex);
                frmShop.Visible = false;
                frmShop.Show();

                raster_type = m_tableName;
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("查询失败:" + ex.Message);
            }
        }
    }
}
